<?php
namespace app\models;

use fastphp\base\Model;
use app\models\User;

class Submit extends Model
{
    public $languages;
    public function init()
    {
        $this->languages = [
            'c++98' => 'C++98',
            'c++11' => 'C++11',
            'c++14' => 'C++14',
            'c++17' => 'C++17',
            'c99' => 'C',
            'python2' => 'Python 2',
            'python3' => 'Python 3',
            'lua' => 'Lua',
            'php7' => 'PHP 7',
            'assembly' => 'Assembly'
        ];
        return $this;
    }
    public function submit($problem, $language, $code)
    {
        // Insert into database
        $rid = (new Record())->doInsertAndGetLast([
            'user' => User::getUser()['id'],
            'problem' => $problem,
            'code' => base64_encode($code),
            'language' => $language
        ])['@@IDENTITY'] or die('?');
        (new Record())->where(['digitid='.$rid])->update(['submitid'=>$rid]) or die('?');
        // Send to server
        $connSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (socket_connect($connSocket, '172.45.33.200', 7767) == false){
            die ('connect fail massege: '.socket_strerror(socket_last_error()));
        } else {
            $message = (string) $rid;
            if (socket_write($connSocket, $message, strlen($message)) == false){
                die ('fail to write '.socket_strerror(socket_last_error()));
            }
        }
        socket_close($connSocket);
        header('Location: /record/show/'.$rid);
    }
}